package com.listeningframework.boot.commons.reflect;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * Java Reflect Utils
 * 
 * @author listening
 * @version $Id: ReflectUtils.java, v 0.1 2015年6月11日 下午10:36:56 listening Exp $
 */
public class BeanUtils {
    private static final Logger logger = LoggerFactory.getLogger(BeanUtils.class);

    /**
     * Copy Object Properties
     * 
     * @param srcObj 源对象
     * @param <T> 泛型参数
     * @param resultClz 目标Class
     * @return T
     */
    public static final <T> T copy(Object srcObj, Class<T> resultClz) {
        T result = null;
        try {
            result = resultClz.newInstance();
        } catch (InstantiationException e) {
            logger.error("", e);
        } catch (IllegalAccessException e) {
            logger.error("", e);
        }
        if (result == null) {
            throw new RuntimeException("can not instance the class ->" + resultClz.getName());
        }
        try {
            org.springframework.beans.BeanUtils.copyProperties(srcObj, result);
            return result;
        } catch (Exception e) {
            throw new RuntimeException("copy properties fail", e);
        }
    }

    /**
     * Copy source properties to dest object
     *
     * @param source 源对象
     * @param dest 目标对象
     * @return Object
     */
    public static final Object copy(Object source, Object dest) {
        try {
            org.springframework.beans.BeanUtils.copyProperties(source, dest);
            return dest;
        } catch (Exception e) {
            throw new RuntimeException("copy properties fail", e);
        }
    }

    /**
     * Set Property Value
     *
     * @param bean 源对象
     * @param name 属性
     * @param value 值
     */
    public static final void setProperty(Object bean, String name, Object value) {
        try {
            org.apache.commons.beanutils.BeanUtils.setProperty(bean, name, value);
        } catch (Exception e) {
        }
    }

}
